#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include "freertos/FreeRTOS.h"
#include "freertos/task.h"
#include "esp_system.h"
#include "esp_log.h"
#include "uart.h"
#include "button.h"

// 全局常量, 字符串, 用于日志打印的标签
const static char *TAG = "UART";

static void uart_rx_task(void *arg)
{
    uint8_t* data = (uint8_t*) malloc(2048);
    while (1) {
        const int rxBytes = uart_read_bytes(UART_NUM_1, data, 2048, 1000 / portTICK_PERIOD_MS);
        if (rxBytes > 0) {
            data[rxBytes] = 0;
            ESP_LOGI(TAG, "Read %d bytes: '%s'", rxBytes, data);
            ESP_LOG_BUFFER_HEXDUMP(TAG, data, rxBytes, ESP_LOG_INFO);
        }
    }
    free(data);
}

void app_main(void)
{
    uint32_t io_num;

    //按键初始化
    button_init();
    
    //串口初始化
    uart_init();

    //创建串口数据接收任务，堆栈大小4096，最大优先级
    xTaskCreate(uart_rx_task, "uart_rx_task", 4096, NULL, configMAX_PRIORITIES, NULL);

    while(true) {
        // 堵塞读取队列中的数据
        if(xQueueReceive(gpio_evt_queue, &io_num, portMAX_DELAY)) {
            // 读取成功，则打印出gpio引脚号和当前的电平
            ESP_LOGI(TAG, "GPIO[%ld] intr, val: %d", io_num, gpio_get_level(io_num));
            if(io_num==GPIO_INPUT_BOOT)
            {
                uart_write_bytes(UART_NUM_1, "hello\r\n", strlen("hello\r\n"));
            }
        }
    } 
}